﻿using NoiseMonitor.Phone.Mvc.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using NoiseMonitor.Model;
using CubeStone.Wang.Utilities;
using System.IO;
using System.Text.RegularExpressions;

namespace NoiseMonitor.Phone.Controllers
{
    public class HomeController : BaseController
    {
        [AllowAnonymous]
        public ActionResult Login([Bind(Include = "Account,Password")]User user)
        {
            if (string.IsNullOrEmpty(user.Account) || string.IsNullOrEmpty(user.Password))
            {
                return Json(new { State = "Fail", Message = "参数不可为空！" }, JsonRequestBehavior.AllowGet);
            }
            user.Token = HashHelper.MD5(user.Account+user.Password+DateTime.Now.ToString());
            user = db.Login(user);
            if(user.Id == Guid.Empty)
            {
                return Json(new { State = "Fail", Message = "账户名或密码错误！" }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { State = "Ok", Id = user.Id.ToString(), Name = user.Name, Token = user.Token }, JsonRequestBehavior.AllowGet);
        }

        [AllowAnonymous]
        public ActionResult Register([Bind(Include = "Account,Name,Password")]User user)
        {
            if (string.IsNullOrEmpty(user.Account) || string.IsNullOrEmpty(user.Password) || string.IsNullOrEmpty(user.Name))
            {
                return Json(new { State = "Fail", Message = "参数不可为空！" });
            }
            user.Token = HashHelper.MD5(user.Account + user.Password + DateTime.Now.ToString());
            user.Id = Guid.NewGuid();
            user.CreateTime = DateTime.Now;
            if(db.IsExistUser(user.Account))
            {
                return Json(new { State = "Fail", Message="账户名已存在！" });
            }
            else if(db.Register(user))
            {
                return Json(new { State = "Ok", Id = user.Id.ToString(), Token = user.Token });
            }
            else
            {
                return Json(new { State = "Fail", Message = "服务器错误！" });
            }
        }

        public ActionResult UploadRawData([Bind(Include = "Id,Token")]User user, DateTime dateTime)
        {
            dateTime = dateTime.Date;
            if(dateTime < DateTime.Now.Date.AddDays(-1))
            {
                return Json(new { State = "Fail", Message = "两天前的数据不可上传！" }, JsonRequestBehavior.AllowGet);
            }
            List<RawData> list = new List<RawData>();
            StreamReader sr = new StreamReader(Request.InputStream);
            string str;
            string[] array;
            while(!string.IsNullOrEmpty(str = sr.ReadLine()))
            {
                array = str.Split(',');
                if(array.Length != 6)
                {
                    continue;
                }
                RawData rawData = new RawData() 
                { 
                    UserId = user.Id,
                    Longitude = array[0], 
                    Latitude = array[1], 
                    Province = array[2],  
                    City = array[3], 
                    Decibel = array[4], 
                    CreateTime = DateTime.Parse(array[5]) 
                };
                if (!Regex.IsMatch(rawData.Longitude, @"\d{2,3}\.\d{3}") || !Regex.IsMatch(rawData.Latitude, @"\d{2,3}\.\d{3}") || !Regex.IsMatch(rawData.Decibel, @"^\d{2,3}$"))
                {
                    continue;
                }
                else if(string.IsNullOrEmpty(rawData.City) || string.IsNullOrEmpty(rawData.Province))
                {
                    continue;
                }
                else if (rawData.CreateTime.Date != dateTime)
                {
                    continue;
                }
                else
                {
                    list.Add(rawData);
                }
            }
            if(list.Count == 0)
            {
                return Json(new { State = "Fail", Message = "无数据！" }, JsonRequestBehavior.AllowGet);
            }
            else if(db.AddRawData(new Tuple<DateTime,List<RawData>>(dateTime,list)))
            {
                return Json(new { State = "Ok", Message = "上传成功！" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { State = "Fail", Message = "上传失败！" }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
